var express = require('express');
var router = express.Router();
var {Types: {ObjectId}} = require('mongoose')
var {userModel,roleModel} = require('../module/user');
const bcryptjs = require("bcryptjs");
var multiparty = require("multiparty");

router.get('/userlist', async (req, res) => {
    let page = req.query.page
    let pagesize = req.query.pagesize
    let userlist = await userModel.find().populate('role_id')
    let total = userlist.length
    userlist = userlist.slice((page - 1) * pagesize, pagesize * page)
    res.send({userlist, total})
});
router.post('/adduser', async (req, res) => {
    let query = req.body
    console.log(query);
    query.password = bcryptjs.hashSync(query.password)
    await userModel.create(query)
    res.send({code: 201, msg: '添加成功'})
});

router.delete('/del', async (req, res,) => {
    let _id = req.query._id
    await userModel.deleteOne({_id: _id})
    res.send({code: 201, msg: '删除成功'})
});
router.put('/edituser', async (req, res) => {
    let obj = req.body
    await userModel.updateOne({_id: obj._id}, obj)
    res.send({code: 201, msg: '修改成功'})
})
router.put('/setrole', async (req, res) => {
    let obj = req.body
    await userModel.updateOne({_id: obj._id}, {role_id: obj.role_id})
    res.send({code: 201, msg: '分配成功'})
})

router.put('/setpw', async (req, res) => {
    let obj = req.body
    let password = bcryptjs.hashSync(obj.password, 12)
    await userModel.updateOne({_id: obj._id}, {password: password})
    res.send({code: 201, msg: '修改成功'})
})

//上传图片
router.post("/addimg", async (req, res) => {
    let form = new multiparty.Form()

    form.uploadDir = "upload"
    form.parse(req, (err, formData, imgData) => {
        imgpath = imgData.file[0].path
        console.log(imgpath);
        res.send( imgpath )
    })
})

router.get('/rolelist',async(req, res)=>{
    let page = req.query._page
    let pagesize = req.query._limit
    console.log(page,pagesize);
    let data =  await roleModel.find()
    let total = data.length
    data = data.slice((page - 1) * pagesize, pagesize * page)
    // data = data.slice((page - 1) * pagesize, pagesize * page)
    res.send({data,total})
})

router.post('/addrolelist',async(req, res)=>{
    let body = req.body
    console.log(body);
    let data = await roleModel.create(body)
    res.send({data,code:200})
})

router.delete('/delrolelist',async(req, res)=>{
    let _id = req.body
    console.log(_id);
    let data = await roleModel.deleteMany({_id:_id})
    res.send({data,code:200})
})
module.exports = router